<?php
abstract class BaseCtl {
	
	public function BaseCtl(){
		
	}

    public function proceed(){
    	// loadData called assumes we are in postback situation
    	if($this->isPostback()) {
    		$this->loadData();
        	
    		$this->dispatch();
    	}
    }

    abstract public function isPostback();
    abstract public function loadData();

    public function dispatch(){
        try {
            $name = BaseCtl::getPost("metname");
            
            $this->$name();
        }
        catch(Exception $err){
            BaseCtl::addError($err->getMessage());
        }
    }


    public static function getSessionObject($key, $className){
        $val = null;

        $v = BaseCtl::getSession($key);

        if($v == null){
            $val = new $className;
            $_SESSION[$key] = $val;
        }
        else if($v instanceof $className){
            $val = $v;
        }
        else {
            $clname = get_class($v);
            exit("Expected: {$className} however got {$clname}");
        }

        return $val;
    }

    public function redirect($url){
        header("Location: $url");
        exit();
    }

    protected function isFilled($val){
        return $val != null && count(trim($val)) > 0;
    }

    protected function isEmpty($val){
        return ! $this->isFilled($val);
    }
    
    public static function getPost($key){
    	$res = null;
    	
    	if(array_key_exists($key, $_POST)){
    		$res = $_POST[$key];
    	}
    	
    	return $res;
    }
    
    public static function getSession($key){
    	$res = null;
    	
    	if(array_key_exists($key, $_SESSION)){
    		$res = $_SESSION[$key];
    	}
    	
    	return $res;
    }
    
    public function getTestForm(){
    	return BaseCtl::getSessionObject("test.form", "TestForm");
    } 
    
    public function getLoginForm(){
    	return BaseCtl::getSessionObject("login.form", "LoginForm");
    } 
    
    public function getProfileForm(){
    	return BaseCtl::getSessionObject("profile.form", "ProfileForm");
    } 

    public function getEditAlbumForm(){
    	return BaseCtl::getSessionObject("editalbum.form", "EditAlbumForm");
    } 
    
    public function getChownPassForm(){
    	return BaseCtl::getSessionObject("chownpass.form", "ChownPassForm");
    } 
    
    public function getChPassForm(){
    	return BaseCtl::getSessionObject("chpass.form", "ChPassForm");
    } 
    
    public function getEditPictureForm(){
    	return BaseCtl::getSessionObject("editpicture.form", "EditPictureForm");
    } 
    
    public function getEditUserForm(){
    	return BaseCtl::getSessionObject("edituser.form", "EditUserForm");
    } 
    
    public function getConfirmAlbumForm(){
    	return BaseCtl::getSessionObject("confirmalbum.form", "ConfirmAlbumForm");
    } 

    public function getConfirmPictureForm(){
    	return BaseCtl::getSessionObject("confirmpicture.form", "ConfirmPictureForm");
    }

    public function getUsersForm(){
    	return BaseCtl::getSessionObject("usersform.form", "UsersForm");
    }
    
    public function getAlbumsForm(){
    	return BaseCtl::getSessionObject("albumsform.form", "AlbumsForm");
    }
    
    public function getPicturesForm(){
    	return BaseCtl::getSessionObject("picturesform.form", "PicturesForm");
    }
    
    public function getMUploadForm(){
    	return BaseCtl::getSessionObject("mupload.form", "MUploadForm");
    }
    
    public function getRenalbumsForm(){
    	return BaseCtl::getSessionObject("renalbums.form", "RenalbumsForm");
    }
    
    public function getRenpicturesForm(){
    	return BaseCtl::getSessionObject("renpictures.form", "RenpicturesForm");
    }
    
    public function getOrderalbumsForm(){
    	return BaseCtl::getSessionObject("orderalbums.form", "OrderalbumsForm");
    }
    
    public function getMovealbumsForm(){
    	return BaseCtl::getSessionObject("movealbums.form", "MovealbumsForm");
    }
    
    public function getJoblistForm(){
    	return BaseCtl::getSessionObject("joblist.form", "JoblistForm");
    }
    
    public function getJobeditForm(){
    	return BaseCtl::getSessionObject("jobedit.form", "JobeditForm");
    }
    
    public function getJobselectForm(){
    	return BaseCtl::getSessionObject("jobselect.form", "JobselectForm");
    }
    
    public function login(){
		try {
			$this->redirect('index.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function logout(){
		try {
			// empty the session
			// then redirect to the login page
			$nr = count($_SESSION);
			array_splice($_SESSION, 0, $nr);

			$this->redirect('index.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function profile(){
		try {
			// get the user from the session
			// fill out the items in the profile form
			// proceed
			$form = $this->getProfileForm();
			
			$s = HtmlUtil::getSessionUser();
			$usr = $s->getUser();
			
			$form->setLogin($usr->getLogin());
			$form->setName($usr->getName());
			$form->setConnect($usr->isConnect());
			$form->setAdmin($usr->isAdmin());
			$form->setEmail($usr->getEmail());
			$form->setSendEmail($usr->isSendEmail());

			$this->redirect('profile.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	// the function renumbers the albums belonging to an user
	// to ensure that there aren't two with the same sequence id
	public function renalbums(){
		try {
			$this->redirect('renalbums.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	// the function renumbers the pictures in an album
	public function renpictures(){
		try {
			$this->redirect('renpictures.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function albums(){
		try {
			$this->redirect('albums.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function users(){
		try {
			$service = new Service(); 
			$users = $service->getUsers();

			$form = $this->getUsersForm();
			
			$form->setSelected(array());
			$form->setUsers($users);
			
			$this->redirect('users.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	protected function checkPassword($provided, $recorded){
		$prov = $this->isEmpty($provided) ? '' : md5(trim($provided));
		$rec = $this->isEmpty($recorded) ? '' : $recorded;
		
		// either we compare the hashed values 
		// or if the values are empty we don't hash
		return ($prov == $rec);
	}
	
	/**
	 * check whether file exists
	 * 
	 * @param unknown_type $request the request name that should hold the file
	 */
	public function fileExists($request){
		$res = false;

		if(array_key_exists($request, $_FILES)){
			$file = $_FILES[$request];
			
			if(array_key_exists('error', $file)){
				if($file['error'] <= 0){
					$res = true;
				}
			}
			else {
				if($file['size'] > 0){
					$res = true;
				}
			}
		}
		
		return $res; 
	}

	/**
	 * 
	 * Processes the file to create the three ones - the unchanged one, 
	 * the regular and the smaller
	 * @param unknown_type $request the request key
	 * @param unknown_type $id the id associated with the picture
	 */
	public function processFile($fl, $id){
		$ok = true; 
		// then move existent file from the current location to the <<folder>>/full_$id.dat
		$folder = PictureConfig::$CONTENT_FOLDER;
		
		$destination = "{$folder}pictures/full_{$id}.dat"; 
		move_uploaded_file($fl['tmp_name'], $destination);
		
		// then resize it to the regular position
		$reg = "{$folder}pictures/reg_{$id}.dat";
		$small = "{$folder}pictures/small_{$id}.dat";
		
		$util = new ImageUtil();
		
		try {
			$util->loadImage($destination); 
			$util->saveImage($reg, 640);
			$util->saveImage($small, 150);
		}
		catch(Exception $e){
			$ok = false; 
			
			HtmlUtil::addError($e->getMessage());
		}
		
		try {
			$util->destroy(); // remove the created values
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
		
		return $ok;
	}
	
	/**
	 * delete files associated with the ids in the specified array
	 * 
	 * Enter description here ...
	 * @param unknown_type $ids
	 */
	public function deleteFiles($ids){
		$folder = PictureConfig::$CONTENT_FOLDER;
		
		$arr = array();
		foreach($ids as $id){
			$arr[] = "{$folder}pictures/full_{$id}.dat";
			$arr[] = "{$folder}pictures/reg_{$id}.dat";
			$arr[] = "{$folder}pictures/small_{$id}.dat";
		}
		
		foreach($arr as $file){
			if(file_exists($file)){
				unlink($file);
			}
		}
	}
	
	public function checkLogged(){
		$s = HtmlUtil::getSessionUser(); 
		
		if(! $s->isLogged()){
			HtmlUtil::addError('User not logged in or session expired');
			
			$this->redirect('index.php');
		}
	}
	
	public function checkAdmin(){
		$s = HtmlUtil::getSessionUser(); 
		
		if(! $s->isAdmin()){
			HtmlUtil::addError('Resource restricted for administrators');
			
			$this->redirect('index.php');
		}
	}
	
	public function checkNotReadonly(){
		$s = HtmlUtil::getSessionUser(); 
		
		if($s->isReadonly()){
			HtmlUtil::addError('Resource restricted during readonly operation');
			
			$this->redirect('index.php');
		}
	}
	
	public function getNonEmpty($val){
    	$res = array();
    	
    	if(is_array($val) && count($val) > 0){
    		foreach($val as $current){
    			if(strlen(trim($current)) > 0){
    				$res[] = $current;
    			}
    		}
    	}
    	
    	return $res;
    }
    
    public function orderalbums(){
    	try {
    		// get the form
    		$id = HtmlUtil::getSessionUser()->getUser()->getId();
    		
    		$form = $this->getOrderalbumsForm(); 
    		$form->clear();
    		
    		$service = new Service();
    		$items = $service->searchAlbums($id, '');
    		
    		$form->setItems($items);
    		
    		$this->redirect('orderalbums.php');
    	}
    	catch(Exception $e){
    		HtmlUtil::addError($e->getMessage());
    	}
    }
    
    public function movealbums(){
    	try {
    		$service = new Service();
    		$users = $service->getUsers();
    		
    		$form = $this->getMovealbumsForm();
    		$form->clear();
    		$form->setUsers($users);
    		
    		$this->redirect('movealbums.php');
    	}
    	catch(Exception $e){
    		HtmlUtil::addError($e->getMessage());
    	}
    }
    
    public function joblist(){
    	try {
    		$userId = HtmlUtil::getSessionUser()->getUser()->getId(); 
    		
    		$service = new Service();
    		$jobs = $service->getJobs($userId);
    		
    		$form = $this->getJoblistForm();
    		$form->clear();
    		
    		$form->setJobs($jobs);
    		
    		$this->redirect('joblist.php');
    	}
    	catch(Exception $e){
    		HtmlUtil::addError($e->getMessage());
    	}
    }
    
    protected function getSelected($key){
    	$obj = $this->getPost($key); 
    	$res = array();

    	if(is_array($obj)){
    		foreach($obj as $current){
    			$res[$current] = 'sel';
    		}
    	}
    	
    	return $res; 
    }
    
}
?>
